package com.baoyouqun.API.wx;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.cola.dto.SingleResponse;
import com.baoyouqun.entity.User;
import com.baoyouqun.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;

@Service
@Slf4j
public class WxMiniLoginServiceImpl implements WxMiniLoginService {

    @Resource
    private WxMaService wxMaService;

    @Resource
    private UserService userService;

    @Value("${wechat.appid}")
    private String appid;

    @Value("${wechat.secret}")
    private String secret;

    /**
     * 微信小程序授权登录
     *
     * @param code 微信登录code
     * @return 登录结果，包含用户信息和登录状态
     */
    @Override
    public SingleResponse<WxLoginResultDTO> miniProgramLogin(String code) {
        try {
            // 1. 使用code获取session_key和openid
            WxMaJscode2SessionResult sessionResult = wxMaService.jsCode2SessionInfo(code);
            String openid = sessionResult.getOpenid();
            String sessionKey = sessionResult.getSessionKey();
            String unionid = sessionResult.getUnionid();

            log.info("微信小程序登录，openid: {}", openid);

            // 2. 检查用户是否已注册
            User user = userService.selectByWxOpenid(openid);


            WxLoginResultDTO result = new WxLoginResultDTO();
            result.setOpenid(openid);

            if (user == null) {
                // 3. 未注册，返回未注册状态
                result.setRegistered(false);
                return SingleResponse.of(result);
            }
            if (Objects.equals(user.getLogout(), Boolean.TRUE)) {
                return SingleResponse.buildFailure("300010", "用户账号已注销");
            }
            // 4. 已注册，处理登录逻辑
            result.setRegistered(true);
            result.setUserId(user.getId());
            result.setImUserSig(user.getImUserSig());

            // 5. 判断是否首次登录
            boolean isFirstLogin = user.getLastLoginTime() == null;
            result.setFirstLogin(isFirstLogin);

            // 6. 更新用户登录信息
            user.setLastLoginTime(LocalDateTime.now());
            user.setUnionid(unionid);
            user.setWxSessionKey(sessionKey);
            userService.updateById(user);

            // 7. 使用SaToken创建登录态
            StpUtil.login(user.getId());
            result.setToken(StpUtil.getTokenValue());

            return SingleResponse.of(result);
        } catch (Exception e) {
            log.error("微信小程序登录失败", e);
            return SingleResponse.buildFailure("300010", "微信登录失败，请稍后重试");
        }
    }

    /**
     * 完善用户信息
     *
     * @param userId    用户ID
     * @param nickName  昵称
     * @param avatarUrl 头像URL
     * @param gender    性别
     * @return 操作结果
     */
    @Override
    public SingleResponse<Void> completeUserInfo(Long userId, String nickName, String avatarUrl, Integer gender) {
        try {
            // 1. 校验登录状态
            if (!StpUtil.isLogin() || !StpUtil.getLoginIdAsString().equals(userId.toString())) {
                return SingleResponse.buildFailure("401", "请先登录");
            }

            // 2. 更新用户信息
            User user = userService.getById(userId);
            if (user == null) {
                return SingleResponse.buildFailure("300011", "用户不存在");
            }

            user.setName(nickName);
            user.setHeadImg(avatarUrl);
            userService.updateById(user);

            return SingleResponse.buildSuccess();
        } catch (Exception e) {
            log.error("完善用户信息失败", e);
            return SingleResponse.buildFailure("300012", "完善信息失败，请稍后重试");
        }
    }
}